package com.redpill.linpro.service.impl;

import javax.inject.Inject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.redpill.linpro.integration.Account;
import com.redpill.linpro.integration.AccountRepository;
import com.redpill.linpro.integration.Amount;
import com.redpill.linpro.service.AccountService;

@Service
public class AccountServiceImpl implements AccountService {

	private final AccountRepository accountRepository;

	private Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);

	@Inject
	public AccountServiceImpl(AccountRepository accountRepository) {
		this.accountRepository = accountRepository;
	}

	@Transactional
	public boolean transferAmount(final Amount amount,
			final Account debitAccount, final Account creditAccount) {
		final boolean transferred;
		
		final Amount debitAccountBalance = accountRepository
				.getBalance(debitAccount);
		
		logger.debug("Balance on debit account before transfer: {}", debitAccountBalance.getAmount()); 

		if (debitAccountBalance.isLargerThanOrEqualTo(amount)) {
			debitAmount(amount, debitAccount);
			creditAmount(amount, creditAccount);

			transferred = true;
			logger.info("{} was transferred from {} to {}",
					new Object[] { amount, debitAccount, creditAccount });
		} else {
			transferred = false;
			logger.info("The transfer {} is higher than the balance available on the debit account", amount.getAmount());
		}
		
		return transferred;
	}
	
	void debitAmount(final Amount amount, final Account debitAccount) {
		final Amount debitAmount = new Amount(-amount.getAmount());
		
		accountRepository.updateBalance(debitAmount, debitAccount);
	}
	
	void creditAmount(final Amount amount, final Account creditAccount) {
		if (accountRepository.isAccountExisting(creditAccount)) {
			accountRepository.updateBalance(amount, creditAccount);
		}
		else {
			throw new IllegalArgumentException(creditAccount + " doesn't exist in repository");
		}		
	}	
}


